﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Web.Mvc;
using System.Web.Routing;

using mvcForum.Core;
using mvcForum.Core.Abstractions.Interfaces;
using mvcForum.Web.Controllers;
using mvcForum.Web.ViewModels;
using mvcForum.Web.ViewModels.Create;
using mvcForum.Web.Areas.ForumAdmin.Helpers;
using mvcForum.Web.Interfaces;
using mvcForum.Core.Interfaces.Data;

namespace mvcForum.Web.Areas.ForumAdmin.Controllers {

	public class AccessMaskController : ForumAdminBaseController {
		private readonly IRepository<Board> boardRepo;
		private readonly IRepository<AccessMask> masksRepo;

		public AccessMaskController(IWebUserProvider userProvider, IContext context)
			: base(userProvider, context) {

			this.boardRepo = this.GetRepository<Board>();
			this.masksRepo = this.GetRepository<AccessMask>();
		}

		#region Create
		public ActionResult Create(int id) {
			// TODO: Access !?!?
			Board board = this.boardRepo.Read(id);
			var model = new CreateAccessMaskViewModel { BoardId = board.Id };
			return View(model);
		}

		[HttpPost]
		public ActionResult Create(CreateAccessMaskViewModel model) {
			// TODO: Access !?!?
			if (ModelState.IsValid) {
				Board board = this.boardRepo.Read(model.BoardId);
				AccessMask mask = new AccessMask(board, model.Name, AccessFlag.Read);
				this.masksRepo.Create(mask);
				this.Context.SaveChanges();

				return RedirectToAction("Edit", "Board", new RouteValueDictionary { { "id", board.Id } });
			}
			return View(model);
		}
		#endregion

		#region Read/Update
		[Authorize(Roles = Constants.Roles.Combined)]
		public ActionResult Update(int id) {
			// TODO: Access!?!?
			AccessMask mask = this.masksRepo.Read(id);

			return View(new mvcForum.Web.Areas.ForumAdmin.ViewModels.AccessMask { Id = mask.Id, Path = BreadcrumbHelper.BuildPath(mask, Url) });
		}
		#endregion
	}
}